// 路径: com.reliable.service.controller.ChunkUploadController
package com.reliable.service.controller;

import com.reliable.api.param.MergeRequest;
import com.reliable.common.core.domain.AjaxResult;
import com.reliable.service.service.ChunkService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

@Api(tags = "分片上传接口")
@RestController
@RequestMapping("/reliable/chunk-upload")
@Slf4j
public class ChunkUploadController {

    @Autowired
    private ChunkService chunkService;

    @PostMapping("/check")
    @ApiOperation("检查已上传分片（断点续传）")
    public AjaxResult checkUpload(@RequestParam String fileHash) {
        List<Integer> uploaded = chunkService.getUploadedChunks(fileHash);
        Map<String, Object> result = new HashMap<>();
        result.put("uploadedChunks", uploaded);
        return AjaxResult.success(result);
    }

    @PostMapping("/chunk")
    @ApiOperation("上传单个分片")
    public AjaxResult uploadChunk(
        @RequestParam MultipartFile chunk,
        @RequestParam String fileHash,
        @RequestParam int chunkIndex,
        @RequestParam String originalFilename
    ) throws IOException {
        chunkService.saveChunk(chunk, fileHash, chunkIndex, originalFilename);
        return AjaxResult.success();
    }

    @PostMapping("/merge")
    @ApiOperation("合并分片并开始解析导入")
    public AjaxResult mergeAndImport(@RequestBody MergeRequest req) {
        // ✅ 立即提交异步任务
        CompletableFuture.runAsync(() -> {
            try {
                chunkService.mergeAndImportExcel(req.getFileHash(), req.getOriginalFilename(), req.getTaskId());
                log.info("✅ 分片合并与导入任务已完成");
            } catch (Exception e) {
                log.error("❌ 分片合并与导入任务失败", e);
                // 可选：发送告警、更新记录状态为失败等
            }
        });

        // ✅ 立即返回，不等待
        return AjaxResult.success("合并成功，导入任务已提交");
    }
}